from django.shortcuts import render
from django.views import View
from django import http
from django_redis import get_redis_connection

from meiduo_mail.utils.views import LoginRequireJSONMixin
from decimal import Decimal
from apps.users.models import Address
from apps.goods.models import SKU


# Create your views here.


class OrderSettlementView(LoginRequireJSONMixin, View):
    '''结算订单GET /orders/settlement/'''
    def get(self, request):
        user = request.user
        try:
            address_list = Address.objects.filter(user_id=user.id,is_delete=False)
        except Address.DoesNotExist:
            address_list = None
        redis_conn = get_redis_connection('carts')
        select_sku_ids = redis_conn.smembers('selected_%s' % user.id)
        sku_count_dict = redis_conn.hgetall('carts_%s' % user.id)
        cart_dict = {}
        for sku_id in select_sku_ids:
            cart_dict[int(sku_id)] = int(sku_count_dict[sku_id])
        sku_ids = cart_dict.keys()
        select_skus = SKU.objects.filter(id__in=sku_ids)
        skus = []
        for sku in select_skus:
            skus.append({
                "id": sku.id,
                "name": sku.name,
                "default_image_url": sku.default_image.url,
                "count": cart_dict[sku.id],
                "price": sku.price,
            })
        addresses = []
        for address in address_list:
            addresses.append({
                "id": address.id,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "receiver": address.receiver,
            })
        freight = Decimal('10.00')
        context = {"addresses":addresses, "skus": skus, "freight":freight}
        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'context': context})
